//
//  OAuthViewController.swift
//  SinaWeibo
//
//  Created by 张洪毓 on 15/11/9.
//  Copyright © 2015年 张洪毓. All rights reserved.
//

/*
尊敬的微博开放平台开发者“张_Sir”您好：
您于2015/11/09在微博开放平台创建了应用“ZhangSir的Swift微博”，请妥善保管以下应用信息，以免泄露被他人利用：
App key：3927204788
App secret：69fa2bf4654d9cb552bbb6242aac22b2
请仔细参考以下信息，开发并完善您的应用，以满足条件进行提交审核：
应用审核指南：
http://t.cn/amvicS
平台新版API文档：
http://t.cn/zTSZ9D4
粉丝服务平台开发接口介绍：
http://t.cn/8sTxFsW
注：调用粉丝服务API接口无需应用过审，创建应用后可直接调用粉丝服务API接口；
平台SDK资源下载：
http://t.cn/a82ek0
OAuth2.0授权文档：
http://t.cn/zWgMZl6
应用、接口及其他常见问题：
http://t.cn/zT9RmFU
再次感谢您对微博开放平台的支持！
*/

import UIKit
import SVProgressHUD
import AFNetworking
class OAuthViewController: UIViewController {
    
    let webView = UIWebView()
    
    override func loadView() {
        view = webView
        webView.delegate = self
    }
    
    @objc private func close() {
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    @objc private func fillAccount() {
        let jsString = "document.getElementById('userId').value = 'hongyu59425' , document.getElementById('passwd').value = 'hongyu110'"
        webView.stringByEvaluatingJavaScriptFromString(jsString)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupUI()
        loadOauthPage()
    }
    
    
    override func viewDidDisappear(animated: Bool) {
        super.viewDidDisappear(animated)
//        SVProgressHUD.dismiss()
    }
    
    //MARk:  加载授权页面
    private func loadOauthPage() {

        let urlString = "https://api.weibo.com/oauth2/authorize?" + "client_id=" + client_id + "&redirect_uri=" + redirect_uri
        let url = NSURL(string: urlString)
        let request = NSURLRequest(URL: url!)
        webView.loadRequest(request)
    }
    
    private func setupUI() {
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "close")
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动登陆", style: .Plain, target: self, action: "fillAccount")
    }
}
/*
登录成功
Optional(https://api.weibo.com/oauth2/authorize?client_id=3927204788&redirect_uri=https://www.baidu.com)
Optional(https://api.weibo.com/oauth2/authorize)
Optional(https://api.weibo.com/oauth2/authorize#)
Optional(https://api.weibo.com/oauth2/authorize)
Optional(https://www.baidu.com/?code=f9e68c974a78bec54a23aa9da310fedb)
Optional(about:blank)
*/

extension OAuthViewController: UIWebViewDelegate {
    
    func webViewDidStartLoad(webView: UIWebView) {
//        SVProgressHUD.show()
    }
    func webViewDidFinishLoad(webView: UIWebView) {
//        SVProgressHUD.dismiss()
    }
    // 返回ture表示对象能正常工作
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        //        print(request.URL)
        guard let urlString = request.URL?.absoluteString else {
            return false
        }
        if urlString.hasPrefix("https://api.weibo.com") {
            return true
        }
        
        if !urlString.hasPrefix(redirect_uri) {
            return false
        }
        
//        print("wolaidayin:;-----\(request.URL?.query)")
        
        guard let query = request.URL?.query else {
            return false
        }
        
        let codeStr = "code="
        let code = query.substringFromIndex(codeStr.endIndex)
        //        print(codeStr.startIndex)
        //        print(codeStr.endIndex)
        //        print(query)
        //        print(code)
        

        UserAccountViewModel().loadAccessToken(code) { (error) -> () in
//            print("错误回调")

            if error != nil {
                SVProgressHUD.showSuccessWithStatus(AppErrorTip)
                return
            }
            print("come here")
            self.dismissViewControllerAnimated(true, completion: { () -> Void in
                NSNotificationCenter.defaultCenter().postNotificationName(appSwitchRootViewcontroller, object: "welcome")
            })
        }
        
        return false
    }

}







